package com.nchu.commondevelopmentframework.common.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.nchu.commondevelopmentframework.common.constant.ApiCodeConstant;
import com.nchu.commondevelopmentframework.common.domain.ApiResult;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @className: AuthEntryPointHandler
 * @description: 自定义用户未登录的处理（未携带token）
 * @author: Li Chuanwei
 * @date: 2024/02/08 1:00
 * @Company: Copyright [日期] by [作者或个人]
 **/

@Component
public class AuthEntryPointHandler implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        String value = new ObjectMapper().writeValueAsString(ApiResult.fail(ApiCodeConstant.NOT_TOKEN,"未携带认证参数！"));
        response.getWriter().write(value);
    }
}
